//
//  GKZYModifyUserInformationViewController.m
//  GKZYAid
//
//  Created by lanou3g on 16/3/14.
//  Copyright © 2016年 GKZYAid. All rights reserved.
//

#import "GKZYModifyUserInformationViewController.h"

@interface GKZYModifyUserInformationViewController ()

@end

@implementation GKZYModifyUserInformationViewController

- (void)loadView
{
    self.modifyView = [[GKZYModifyUserInformationView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = self.modifyView;
}

- (void)viewDidLoad {
    
    [self downloadUserMessage];
    
    [super viewDidLoad];
    self.title = @"修改资料";
    
    [self.modifyView.buttonSave addTarget:self action:@selector(buttonSaveAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    [tap addTarget:self action:@selector(tapAction:)];
    [self.modifyView.userHeadPortrait addGestureRecognizer:tap];
    
    [self setDelegate];
    
}

//设置代理
- (void)setDelegate
{
    self.modifyView.textViewMotto.delegate = self;
    self.modifyView.userName.LTTextField.delegate = self;
    self.modifyView.userAge.LTTextField.delegate = self;
    self.modifyView.userSex.LTTextField.delegate = self;
    self.modifyView.userSign.LTTextField.delegate = self;
    self.modifyView.userIdeal.LTTextField.delegate = self;
}

//获取用户信息
- (void)downloadUserMessage
{
    AVQuery *query = [AVQuery queryWithClassName:@"UserInformation"];
    [query getObjectInBackgroundWithId:self.userObjectId block:^(AVObject *object, NSError *error) {
        if (!error) {
            self.userObject = object;
            [self setTextFiledText];
        }else{
            NSLog(@"%@",error);
        }
    }];
}

//textFiled赋值
- (void)setTextFiledText
{
    AVFile *userIcon = [self.userObject[@"localData"] objectForKey:@"userImage"];
    [userIcon getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
        if (data) {
            self.modifyView.userHeadPortrait.image = [UIImage imageWithData:data];
        }else{
            NSLog(@"%@",error);
        }
    } progressBlock:^(NSInteger percentDone) {
    }];
    self.modifyView.userName.LTTextField.text = [self.userObject[@"localData"] objectForKey:@"userName"];
    self.strUserNamePrimary = [self.userObject[@"localData"] objectForKey:@"userName"];
    self.modifyView.userSex.LTTextField.text = [self.userObject[@"localData"] objectForKey:@"userSex"];
    self.modifyView.userAge.LTTextField.text = [self.userObject[@"localData"] objectForKey:@"userAge"];
    self.modifyView.userSign.LTTextField.text = [self.userObject[@"localData"] objectForKey:@"userSign"];
    self.modifyView.userIdeal.LTTextField.text = [self.userObject[@"localData"] objectForKey:@"userIdeal"];
    self.modifyView.textViewMotto.text = [self.userObject[@"localData"] objectForKey:@"userMotto"];
    if ([self.modifyView.textViewMotto.text isEqualToString:@"请输入座右铭"]) {
        self.modifyView.textViewMotto.textColor = [UIColor lightGrayColor];
    }else{
        self.modifyView.textViewMotto.textColor = [UIColor blackColor];
    }
}

//添加手势,更换头像
- (void)tapAction:(UITapGestureRecognizer *)sender
{
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    pickerController.allowsEditing = YES;
    pickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    [self presentViewController:pickerController animated:YES completion:nil];
}

//ImagePickerController代理事件
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    self.modifyView.userHeadPortrait.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    self.imageUserHeaderPortrait = self.modifyView.userHeadPortrait.image;
    [self dismissViewControllerAnimated:YES completion:nil];
}

//ImagePickerController代理事件
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//保存按钮
- (void)buttonSaveAction:(UIButton *)sender
{
    self.modifyView.scrollV.contentOffset = CGPointMake(0, 0);
    [self textFieldResignFirstResponder];
    [self addActivityIndicatorView];
    [self getUserMessage];
    [self.userObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            [self removeActivityIndicatorView];
            DataSaveSucceedView *succeedView = [[DataSaveSucceedView alloc] initWithFrame:[UIScreen mainScreen].bounds];
            [succeedView addAnimationOnViewController:self title:@"保存成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.userImageBlock(self.modifyView.userHeadPortrait.image);
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            NSLog(@"%@",error);
        }
    }];
    [self addActivityIndicatorView];
}

//添加活动指示器
- (void)addActivityIndicatorView
{
    UIView *view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [view setTag:108];
    [view setBackgroundColor:[UIColor blackColor]];
    [view setAlpha:0.5];
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 32, 32)];
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
    [self.activityIndicator setCenter:view.center];
    [self.activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [view addSubview:self.activityIndicator];
    [self.activityIndicator startAnimating];
    [self.modifyView addSubview:view];
}

//移除活动指示器
- (void)removeActivityIndicatorView
{
    [self.activityIndicator stopAnimating];
    UIView *view = (UIView*)[self.view viewWithTag:108];
    [view removeFromSuperview];
}

- (void)textFieldResignFirstResponder
{
    [self.modifyView.userName.LTTextField resignFirstResponder];
    [self.modifyView.userSex.LTTextField resignFirstResponder];
    [self.modifyView.userAge.LTTextField resignFirstResponder];
    [self.modifyView.userSign.LTTextField resignFirstResponder];
    [self.modifyView.userIdeal.LTTextField resignFirstResponder];
    [self.modifyView.textViewMotto resignFirstResponder];
}

- (void)getUserMessage
{
    [self changeUserNameOnUserTable];
    
    [self changeUserNameOnPostBar];
    
    HelperModifyUserIconSize *helper = [[HelperModifyUserIconSize alloc] init];
    self.imageUserHeaderPortrait = [helper modifyUserHeaderPortraitSize:self.imageUserHeaderPortrait WithImageWidth:self.imageUserHeaderPortrait.size.width * 0.3 imageHeight:self.imageUserHeaderPortrait.size.height * 0.3];
    
    NSData *imageData = UIImagePNGRepresentation(self.modifyView.userHeadPortrait.image);
    AVFile *file = [AVFile fileWithData:imageData];
    [self.userObject setObject:file forKey:@"userImage"];
    [self.userObject setObject:self.modifyView.userName.LTTextField.text forKey:@"userName"];
    [self.userObject setObject:self.modifyView.userSex.LTTextField.text forKey:@"userSex"];
    [self.userObject setObject:self.modifyView.userAge.LTTextField.text forKey:@"userAge"];
    [self.userObject setObject:self.modifyView.userSign.LTTextField.text forKey:@"userSign"];
    [self.userObject setObject:self.modifyView.userIdeal.LTTextField.text forKey:@"userIdeal"];
    [self.userObject setObject:self.modifyView.textViewMotto.text forKey:@"userMotto"];
}

- (void)changeUserNameOnUserTable
{
    [[AVUser currentUser] setObject:self.modifyView.userName.LTTextField.text forKey:@"username"];
    [[AVUser currentUser] saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (error) {
            NSLog(@"%@",error);
        }
    }];
}

- (void)changeUserNameOnPostBar
{
    AVQuery *queryPublicationUserName = [PostBar query];
    [queryPublicationUserName whereKey:@"strPublicationUserName" equalTo:self.strUserNamePrimary];
    [queryPublicationUserName findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        for (PostBar *postBar in objects) {
            [postBar setObject:[AVUser currentUser].username forKey:@"strPublicationUserName"];
            [postBar save:&error];
            if (error) {
                NSLog(@"%@",error);
            }
        }
    }];
    
    AVQuery *queryCommentUserName = [PostBar query];
    [queryCommentUserName whereKey:@"strCommentUserName" equalTo:self.strUserNamePrimary];
    [queryCommentUserName findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        for (PostBar *postBar in objects) {
            [postBar setObject:[AVUser currentUser].username forKey:@"strCommentUserName"];
            [postBar save:&error];
            if (error) {
                NSLog(@"%@",error);
            }
        }
    }];
    
    AVQuery *queryReplyUserName = [PostBar query];
    [queryReplyUserName whereKey:@"strReplyUserName" equalTo:self.strUserNamePrimary];
    [queryReplyUserName findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        for (PostBar *postBar in objects) {
            [postBar setObject:[AVUser currentUser].username forKey:@"strReplyUserName"];
            [postBar save:&error];
            if (error) {
                NSLog(@"%@",error);
            }
        }
    }];
    
    AVQuery *queryPassivityReplyUserName = [PostBar query];
    [queryPassivityReplyUserName whereKey:@"strPassivityReplyUserName" equalTo:self.strUserNamePrimary];
    [queryPassivityReplyUserName findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        for (PostBar *postBar in objects) {
            [postBar setObject:[AVUser currentUser].username forKey:@"strPassivityReplyUserName"];
            [postBar save:&error];
            if (error) {
                NSLog(@"%@",error);
            }
        }
    }];
    
}

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if ([textView.text isEqualToString:@"请输入座右铭"]) {
        textView.text = nil;
    }
    self.modifyView.scrollV.contentOffset = CGPointMake(0, textView.tag - 101);
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    textView.contentOffset = CGPointMake(0, 0);
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.modifyView.userName.LTTextField resignFirstResponder];
    [self.modifyView.userSex.LTTextField resignFirstResponder];
    [self.modifyView.userAge.LTTextField resignFirstResponder];
    [self.modifyView.userSign.LTTextField resignFirstResponder];
    [self.modifyView.userIdeal.LTTextField resignFirstResponder];
    [self.modifyView.textViewMotto resignFirstResponder];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    self.modifyView.scrollV.contentOffset = CGPointMake(0, textField.tag - 101);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
